package auditoryUI;
import java.io.*;
import java.text.DateFormat;
import java.util.*;
import fr.emn.utils.GeneralTimer;

/**
 * @author Shengdong Zhao
 * University of Toronto
 * mSpace Project
 *
 */
public class Logger {

	//default path for storing log files.
	private String msFileName;
	
	private SimpleDriver sd;
	
	private String userID;
	private StringBuffer moLogText;
	
	public final static String msSeparator = "\t";
	
	private final String LOG_CONNECTOR = "\t";
	
	static GeneralTimer hirestimer;
	
	static long starttime; 
	
	private int trialNum = -1;
	
	private int blockNum = -1;
	
	private String trialFileName = "";
	
	private String condition = "";

	
	public Logger(){
		moLogText = new StringBuffer();
		hirestimer = new GeneralTimer();
		starttime = (new Date()).getTime();
		hirestimer.reset();
	}

	public String getLogFilename (String file) {
		Calendar calendar = new GregorianCalendar();
		DateFormat localFormat = DateFormat.getDateInstance();
		String date = localFormat.format(calendar.getTime());
		String DIR = "c:\\experimentLog\\" + date + "\\";
		(new File(DIR)).mkdirs();
		String filename = DIR + file + "_" + userID + ".txt";
		return filename;		
	}

	
	/**
	 * Set the trial number for logger.
	 * @param num
	 */
	public void setTrialNum(int num){
		trialNum = num;
	}
	
	/**
	 * Set the block number for logger.
	 * @param num
	 */
	public void setBlockNum(int num){
		blockNum = num;
	}
	
	public void setTrialFileName(String name){
		trialFileName = name;
	}
	
	public void setCondition(String con){
		condition = con;
	}
	 /**
     * 
     * @param actionType: how many action types: fingerTouched, fingerReleased, fingerDragged, 
     * I don't want to log all the drag event, since it might be too much. I only log 
     * the event where the zone of the finger is different from the last event.
     * @param zoneNumber
     */
    public void log(String condition, String actionType, 
    		String item, String status, String goal, int x, int y, int z)
    {
    	String logLine = "";
        //throw new Exception("The method or operation is not implemented.");
        logLine += userID + LOG_CONNECTOR;
        
        logLine += condition + LOG_CONNECTOR;
        
        logLine += trialFileName + LOG_CONNECTOR;
        
        logLine += trialNum + LOG_CONNECTOR;
        
        logLine += blockNum + LOG_CONNECTOR;
        
        // column 3 - condition name 
        logLine += condition + LOG_CONNECTOR;
        
        logLine += status + LOG_CONNECTOR;
        
        logLine += goal + LOG_CONNECTOR;
        
        logLine += item + LOG_CONNECTOR;
        
        logLine += x +","+y+","+z + LOG_CONNECTOR;

       	logLine += actionType + LOG_CONNECTOR;
        
        logLine += getTime();
        
        msFileName = getLogFilename("log");
		LoggerHelper l = new LoggerHelper(msFileName, logLine);
		l.start();
      
    }
    
    public void logHighLevel(int id, long reactionTime, long completeTime, String status){
    	String file = getLogFilename("log");
    	file = file.substring(0,file.indexOf(".txt")) + "_highlog.txt";
    	String line = id + LOG_CONNECTOR + condition + LOG_CONNECTOR + trialFileName + LOG_CONNECTOR 
    	+blockNum + LOG_CONNECTOR + trialNum + LOG_CONNECTOR +  reactionTime + LOG_CONNECTOR
    	+ completeTime + LOG_CONNECTOR +  (completeTime + reactionTime)
    	+ LOG_CONNECTOR + status + "\n";
		LoggerHelper l = new LoggerHelper(file, line);
		l.start();
	}
    
	
	// hi-resolution time!
	public static long getTime() {
		return starttime + hirestimer.getIntTime();
	}
	
	public static String getTimeSinceExperimentStart() {
		int mn = (hirestimer.getIntTime()/1000)/60;
		int h = mn/60;
		mn -= h*60;
		String s;
		if (h > 0) s = "" + h; else s = "0";
		s += ":";
		if (mn > 0) s += ((mn<10)? "0" : "") + mn; else s+= "00";
		return s;
	}
	
	public void setUserID(int id){
		userID = id + "";
	}
	
	private class LoggerHelper extends Thread{
		
		private String filename, content;
		
		private LoggerHelper(String fname, String con){
			filename = fname;
			content = con;
		}
		
		
		public void run(){
			try {
				BufferedWriter out =
					new BufferedWriter(new FileWriter(filename, true));
				//out.write("trial start ---------------------------------------------------------\n");
				out.write(content);
				//out.write("trial end ---------------------------------------------------------\n");
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("Exception happened when trying to open the buffer.");
			}
		}
	}
}
